/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

/**
 *
 * @author gjun
 */
public class BaseDAO {
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (Exception ex) {
            ex.printStackTrace();
            
        }
        
    }
    public Connection getConnection() throws Exception{//參考http://tomcat.apache.org/tomcat-8.0-doc/jndi-resources-howto.html
        Context initCtx = new InitialContext();//JNDI
        Context envCtx = (Context) initCtx.lookup("java:comp/env");
        DataSource ds = (DataSource)
        envCtx.lookup("jdbc/javadb");

        Connection conn = ds.getConnection();
        return conn;
    
    }
    
    
    public int modify(String sql,String ary[])
        {
            int x=0;
                
            try(Connection con = this.getConnection();
            java.sql.PreparedStatement ps=con.prepareStatement(sql);) {//java7 才可以這樣寫
                for(int i =0 ; i < ary.length ; i++)
                    ps.setString(i+1, ary[i]);
                    x =ps.executeUpdate();
                
                } catch (Exception e) {
                e.printStackTrace();
                }
                return x;
           
        }
    public ArrayList query(String sql ,String ary[]){
        ArrayList list= new ArrayList();
        try(Connection con = this.getConnection();
            java.sql.PreparedStatement ps=con.prepareStatement(sql);) {//java7 才可以這樣寫
                for(int i =0 ; i < ary.length ; i++)
                    ps.setString(i+1, ary[i]);
                    ResultSet rs=ps.executeQuery();
                    java.sql.ResultSetMetaData mata=rs.getMetaData();
                    int cols= mata.getColumnCount();//算有幾個欄位
                    while(rs.next()){
                        HashMap data= new HashMap();
                        for(int i=1;i<=cols;i++)
                            data.put(mata.getColumnName(i), rs.getString(i) );
                        list.add(data);
                    }
                    rs.close();
                } catch (Exception e) {
                e.printStackTrace();
                }
        
        return list;
    
    }
}
